package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.tabrepay

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.IApiProcessCallback
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.doPostRequest
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.user.mainProcessFormat
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal
import java.math.RoundingMode

class TabRepayGhanaViewModel : ViewModel() {

    private val _loadingResult = MutableLiveData<Boolean>()
    val loadingResult: LiveData<Boolean> = _loadingResult

    private val _pageDetailResult = MutableLiveData<TabRepayGhanaResult>()
    val pageDetailResult: LiveData<TabRepayGhanaResult> = _pageDetailResult

    private val _plansResult = MutableLiveData<TabRepayGhanaPlansResult>()
    val plansResult: LiveData<TabRepayGhanaPlansResult> = _plansResult

    private val _mainProcessResult = MutableLiveData<TabRepayGhanaMainProcessResult>()
    val mainProcessResult: LiveData<TabRepayGhanaMainProcessResult> = _mainProcessResult

    private val _nextRouterResult =
        MutableLiveData<TabRepayGhanaNextRouterResult<AppCompatActivity>>()
    val nextRouterResult: LiveData<TabRepayGhanaNextRouterResult<AppCompatActivity>> =
        _nextRouterResult

    /** 获取页面详情接口 */
    fun pageDetail() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "lXnRXKfosz8aDOsiPwloxQ"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                val days = obj.optString("days")
                val flexiblePayTips = "Repay at any time, but no longer than $days days"
                obj.put("flexiblePayTips", flexiblePayTips)

                // 金额格式化
                val minAmount = obj.optString("minAmount", "0")
                val availableAmount = obj.optString("availableAmount", "0")
                val utilisedAmount = obj.optString("utilisedAmount", "0")
                val maxAmount = obj.optString("maxAmount", "0")

                // 转成不带.0结尾的值
                val minAmountBigString = BigDecimal(minAmount).stripTrailingZeros().toPlainString()
                val availableAmountBigString =
                    BigDecimal(availableAmount).stripTrailingZeros().toPlainString()
                val utilisedAmountBigString =
                    BigDecimal(utilisedAmount).stripTrailingZeros().toPlainString()
                val maxAmountBigString = BigDecimal(maxAmount).stripTrailingZeros().toPlainString()

                // 更新
                obj.put("minAmount", minAmountBigString)
                obj.put("availableAmount", availableAmountBigString)
                obj.put("utilisedAmount", utilisedAmountBigString)
                obj.put("maxAmount", maxAmountBigString)

                obj.put("sliderAmount", minAmountBigString)
                val minAmountInt = minAmountBigString.toInt()
                val availableAmountInt = availableAmountBigString.toInt()
                if (availableAmountInt < minAmountInt) {
                    obj.put("sliderAmount", "0")
                }

                // 可用百分比
                val availBigDec = BigDecimal(availableAmountBigString)
                val totalBigDec = BigDecimal(maxAmountBigString)
                val processDiv = availBigDec.divide(totalBigDec, 2, RoundingMode.HALF_UP)
                val process = processDiv.stripTrailingZeros().toPlainString()
                val percentMul = processDiv.multiply(BigDecimal("100"))
                val percentText = percentMul.stripTrailingZeros().toPlainString() + "%"
                obj.put("availablePercent", percentText)
                obj.put("availableProcess", process)

                // [[],[]]
                val loanList = obj.optJSONArray("loanList") ?: JSONArray()
                val plan = mutableListOf<JSONObject>()
                for (index in 0 until loanList.length()) {
                    val item = loanList.optJSONObject(index)
                    plan.add(item)
                }
                _pageDetailResult.value = TabRepayGhanaResult(success = obj)
                _plansResult.value = TabRepayGhanaPlansResult(success = plan)

                _loadingResult.value = false
            }

            override fun onApiError(code: String, errMsg: String) {
                _pageDetailResult.value = TabRepayGhanaResult(error = errMsg)
                _loadingResult.value = false
            }
        })

    }


    /** 查询主流程接口 */
    fun mainProcess() {
        _loadingResult.value = true
        val context = ProjectApplication.context
        val action = hashMapOf<String, Any>().createApiAction()
        action["path"] = "D50PrK3UELaosdHcVCL7A"

        context.doPostRequest(action, object : IApiProcessCallback {
            override fun onApiReady() {
            }

            override fun onApiDone(jsonObject: JSONObject) {
                _loadingResult.value = false
                val obj = jsonObject.optJSONObject("obj") ?: JSONObject()
                _mainProcessResult.value = TabRepayGhanaMainProcessResult(success = obj)
            }

            override fun onApiError(code: String, errMsg: String) {
                _loadingResult.value = false
                _mainProcessResult.value = TabRepayGhanaMainProcessResult(error = errMsg)
            }
        })
    }

    /** 页面跳转 */
    fun nextRouter(jsonObject: JSONObject) {
        // 判断下一步
        val nextRouterResult = jsonObject.mainProcessFormat(fromTabRepay = true)
        if (nextRouterResult.nextRouter != null) {
            _nextRouterResult.value =
                TabRepayGhanaNextRouterResult(nextPage = nextRouterResult.nextRouter)
        }
    }
}